const app = getApp()
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request';
import {
  showToast,
  getUrlParam,
  editTabBar,
} from '../../utils/util';
export default function menu() {
  return {
    /**
     * 页面的初始数据
     */
    data: {
      themeColor: app.globalData.themeColor,
      subColor: app.globalData.subColor,
      btnColor: app.globalData.btnColor,
      baseImg: app.globalData.myTestImg,
      paymentPriority: wx.getStorageSync('paymentPriority') || 0, //0先付后吃  1先吃后付
      dataType: 1,
      orderList: [],
      pageNo: 1,
      pageSize: 10,
      loadType: "",
    },

    // tab订单类型改变时
    onTabChange(e) {
      this.setData({
        dataType: e.currentTarget.dataset.index,
      });
      this.initData();
    },
    //阻止冒泡事件
    handmiddle() {

    },

    //前往订单详情页
    toOrderDetailPage(e) {
      let orderId = e.currentTarget.dataset.id;
      wx.navigateTo({
        url: '../orderDetail/orderDetail?orderId=' + orderId,
      })
    },

    //初始化数据
    initData() {
      wx.pageScrollTo({
        scrollTop: 0,
        duration: 10
      })
      let loadType = "";
      if (this.data.loadType == "loadNull") {
        loadType = "loadNull"
      }
      this.setData({
        pageNo: 1,
        pageSize: 10,
        loadType: loadType,
      });
      this.getFoodsOrderList(false);
    },

    //获取订单列表,isConcat 是否拼接
    getFoodsOrderList(isConcat) {
      let that = this;
      postRequest("/api/vip/getFoodsOrderList", {
        beid: app.beid,
        dataType: that.data.dataType,
        memberId: app.myInfo.memberId,
        pageNo: that.data.pageNo,
        pageSize: that.data.pageSize,
      }).then((res) => {
        console.log(res.data.data);
        if (res.data.data != null) {
          //合并数据
          let list = isConcat ? that.data.orderList.concat(res.data.data.data) : res.data.data.data;
          console.log(list);
          //判断是否还有数据
          let loadType = "";
          if (res.data.data.totalCount == 0) {
            loadType = "loadNull";
          } else {
            if (Math.ceil(res.data.data.totalCount / that.data.pageNo) <= that.data.pageSize) {
              loadType = "loadOver";
            } else {
              loadType = "loadMore";
            }
          }

          that.setData({
            orderList: list,
            loadType: loadType,
            pageNo: that.data.pageNo + 1,
          })
          // 停止下拉刷新效果
          wx.stopPullDownRefresh()
        }
      }).catch((err) => {
        // 停止下拉刷新效果
        wx.stopPullDownRefresh();
      });
    },

    //取消订单
    cancelFoodsOrder(e) {
      let that = this;
      wx.showModal({
        title: '提示',
        content: '确认取消订单？',
        confirmText: "是",
        success(res) {
          if (res.confirm) {
            let id = e.currentTarget.dataset.id;
            let param = {
              orderId: id,
            };
            wx.showLoading({
              title: '取消中...',
              icon: 'none',
            })
            postParamsRequest("/api/vip/cancelFoodsOrder", param).then((res) => {
              console.log(res);
              wx.hideLoading();
              that.initData();
            }).catch((err) => {
              wx.hideLoading();
            });
          } else if (res.cancel) {}
        }
      })

    },

    //去支付
    goPayOrder(e) {
      let self = this;
      let id = e.currentTarget.dataset.id;
      wx.showLoading({
        title: '支付中...',
        icon: 'none',
      })
      postParamsRequest("/api/order/payFoodsOrder", {
        orderId: id,
      }).then((res2) => {
        console.log(res2.data.data);
        let data = res2.data.data;
        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign,
          'success': function (res3) {
            console.log(res3);
            wx.hideLoading();
            //刷新页面
            self.initData();
          },
          'fail': function (err) {
            console.log(err);
            wx.hideLoading();
            showToast("支付失败");
          }
        })

      }).catch((err) => {
        wx.hideLoading();
      });
    },

    //删除订单
    delFoodsOrder(e) {
      let that = this;
      let id = e.currentTarget.dataset.id;
      let param = {
        orderId: id,
      };
      wx.showModal({
        title: '提示',
        content: '删除该订单？',
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              title: '删除中...',
              icon: 'none',
            })
            postParamsRequest("/api/vip/delFoodsOrder", param).then((res) => {
              wx.hideLoading();
              that.initData();
            }).catch((err) => {
              wx.hideLoading();
            });
          } else if (res.cancel) {}
        }
      })
    },

    //确认完成，确认收货
    finishOrder(e) {
      let that = this;
      let id = e.currentTarget.dataset.id;
      let orderType = e.currentTarget.dataset.orderType;
      let param = {
        orderId: id,
      };
      wx.showModal({
        title: '提示',
        content: '是否确认完成订单？',
        confirmText: "是",
        success(res) {
          if (res.confirm) {
            wx.showLoading({
              title: '确认中...',
              icon: 'none',
            })
            postParamsRequest("/api/vip/confirmFoodsOrder", param).then((res) => {
              wx.hideLoading();
              that.initData();
            }).catch((err) => {
              wx.hideLoading();
            });
          } else if (res.cancel) {}
        }
      })
    },

    //再来一单
    againOrder(e) {
      console.log(e.currentTarget.dataset.goods);
      let goods = e.currentTarget.dataset.goods;
      let cartList1 = app.globalData.cartList;
      console.log(cartList1);

      // goods.forEach((item, index) => {
      //   let goodsSku = ""
      //   if (item.goodsSku != '') {
      //     let goodsSkuList = item.goodsSku.split("_")
      //     console.log(goodsSkuList);
      //     goodsSkuList.forEach((item, index) => {
      //       if (index == 0) {
      //         goodsSku = '[' + item
      //       } else if (index == goodsSkuList.length - 1) {
      //         goodsSku = goodsSku + ',' + item + ']'
      //       } else {
      //         goodsSku = goodsSku + ',' + item
      //       }
      //     });
      //   }
      //   console.log(goodsSku);
      //   cartList1.push({
      //     checked: true,
      //     id: item.goodsId,
      //     attrList: [],
      //     cateId: item.goodsCateId,
      //     count: item.goodsNum,
      //     goodsId: item.goodsId,
      //     packageList: [],
      //     packageListString: JSON.stringify([]),
      //     skuId: item.skuId,
      //     thumbUrl: item.goodsThumb,
      //     goodsName: item.goodsName,
      //     goodsSkuName: goodsSku,
      //     goodsArrName: item.goodsAttr,
      //     goodsArrIds: item.goodsAttr,
      //     shopPrice: item.goodsPrice,
      //   });

      // });
      // app.globalData.isOpenCart = true;
      wx.switchTab({
        url: '../orderFood/orderFood?openShoppingCart=true'
      })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
      editTabBar(this);
      let that = this;
      //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
      if (app.token == "" || app.token == undefined) {
        app.initLogin().then(res => {
          that.initData()
        }).catch(err => {})
      } else {
        that.initData();
      }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
      this.initData();
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
      if (this.data.loadType == "loadMore") {
        this.setData({
          loadType: "",
        });
        this.getFoodsOrderList(true);
      }
    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
  }
}